package top.lunarye.handler;

import cn.hutool.core.exceptions.StatefulException;
import cn.hutool.core.exceptions.UtilException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import top.lunarye.utils.RestResponse;
import top.lunarye.utils.SystemCode;

import java.util.Arrays;

/**
 * @description: 自定义全局异常处理
 * @author: lunar
 * @since: 2021-07-19
 */
@ControllerAdvice
@Slf4j
public class MyExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public RestResponse exceptionHandler(Exception e) {
        if (e instanceof StatefulException) {
            return RestResponse.fail(SystemCode.AccessTokenError.getCode(), e.getMessage());
        }
        log.error(Arrays.toString(e.getStackTrace()));
        return RestResponse.fail(SystemCode.InnerError.getCode(), e.getMessage());
    }

    /**
     * 用于处理在业务中主动抛出的错误
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = UtilException.class)
    public RestResponse<String> BizExceptionHandler(UtilException e) {
        log.error(Arrays.toString(e.getStackTrace()));
        return RestResponse.fail(SystemCode.InnerError.getCode(), e.getMessage());
    }

}
